import asyncio
import logging
from typing import Dict, Optional
from src.rag import RAG

class ReviewAgent:
    """异步综述生成代理"""
    
    def __init__(self, rag: RAG):
        self.rag = rag
        self.logger = logging.getLogger(__name__)

    async def generate_review(
        self, 
        query: str, 
        review_type: str = 'status'
    ) -> Optional[Dict]:
        """异步执行综述生成"""
        loop = asyncio.get_event_loop()
        try:
            # 异步执行RAG逻辑
            result = await loop.run_in_executor(
                None,
                self.rag.generate_review,
                query,
                review_type,
                50  # default min_papers
            )
            
            if not result:
                self.logger.warning("RAG生成返回空结果，尝试创建基础响应")
                # 创建基础响应，避免返回None
                result = {
                    'content': f"无法生成关于'{query}'的完整综述。请尝试使用更具体的查询或检查系统日志获取详细错误信息。",
                    'citations': []
                }
                
            # 异步后处理（可添加额外验证等）
            return result
            
        except Exception as e:
            self.logger.error(f"异步生成失败: {str(e)}")
            # 返回简洁的错误描述
            return {
                'content': f"生成综述时发生错误: {str(e)}",
                'citations': []
            }
